package com.atstudy.headline.web.app.controller.contents;

import com.atstudy.headline.entity.Categories;
import com.atstudy.headline.entity.ContentHotScore;
import com.atstudy.headline.entity.Contents;
import com.atstudy.headline.entity.Users;
import com.atstudy.headline.enums.BaseStatus;
import com.atstudy.headline.result.Result;
import com.atstudy.headline.web.app.service.CategoriesService;
import com.atstudy.headline.web.app.service.ContentHotScoreService;
import com.atstudy.headline.web.app.service.ContentsService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@CrossOrigin
@RequestMapping("/app/contents")
public class AppContentsController {

    @Autowired
    private ContentsService contentsService;

    @Autowired
    private CategoriesService categoriesService;

    @Autowired
    private ContentHotScoreService contentHotScoreService;

    @GetMapping("/page")
    public Result<Map<String, Object>> pageInfoByComments(@RequestParam Integer current, @RequestParam Integer size){
        Page<Contents> page = new Page<>();
        page.setCurrent(current);
        page.setSize(size);
        IPage<Contents> commentsIPage = contentsService.pageInfoByContents(page);
        List<Categories> list = categoriesService.list();
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("contentsPage", commentsIPage);
        resultMap.put("categoriesList", list);
        return Result.ok(resultMap);
    }


    /**
     * 根据内容ID查询内容详情
     * @param contentId
     * @return
     *     */
    @GetMapping("/{contentId}")
    public Result<Contents> getContentById(@PathVariable Integer contentId){
        return Result.ok(contentsService.getContentById(contentId));
    }

    @GetMapping("/page/{categoryId}")
    public Result<IPage<Contents>> getContentByCategoryId(@RequestParam(defaultValue = "1") Integer current, @RequestParam(defaultValue = "10") Integer size,@PathVariable Integer categoryId){
        Page<Contents> page = new Page<>(current,size);
        IPage<Contents> iPage = contentsService.getContentByCategoryId(page,categoryId);
        return Result.ok(iPage);
    }

    /**
     * 查询内容热度分数表 根据热度分数降序排序 分数类型为2
     * @param
     * @return
     */
    @GetMapping("/hot")
    public Result<List<Contents>> getHotContents() {
        // 1. 查询热度分数表
        LambdaQueryWrapper<ContentHotScore> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(ContentHotScore::getHotScore);
        queryWrapper.eq(ContentHotScore::getScoreType, 2);
        List<ContentHotScore> contentHotScores = contentHotScoreService.list(queryWrapper);

        // 2. 提取内容ID列表
        List<Integer> contentIds = contentHotScores.stream()
                .map(ContentHotScore::getContentId)
                .collect(Collectors.toList());

        if (contentIds.isEmpty()) {
            return Result.ok(Collections.emptyList());
        }

        // 3. 根据内容ID列表查询内容详情
        LambdaQueryWrapper<Contents> contentsQuery = new LambdaQueryWrapper<>();
        contentsQuery.in(Contents::getContentId, contentIds);
        List<Contents> contentsList = contentsService.list(contentsQuery);

        // 4. 按热度分数排序
//        Map<Integer, BigDecimal> contentScoreMap = contentHotScores.stream()
//                .collect(Collectors.toMap(
//                        ContentHotScore::getContentId,
//                        ContentHotScore::getHotScore
//                ));
//
//        contentsList.sort((a, b) -> {
//            BigDecimal scoreA = contentScoreMap.get(a.getContentId());
//            BigDecimal scoreB = contentScoreMap.get(b.getContentId());
//            return scoreB.compareTo(scoreA); // 降序排序
//        });
        return Result.ok(contentsList);
    }



    /**
     * 用户发布的内容
     * @param userId
     * @param current
     * @param size
     * @return
     */
    @GetMapping("/getContentsByUserIdPage/{userId}")
    public Result<IPage<Contents>> getContentsByUserIdPage(
            @PathVariable Integer userId,
            @RequestParam(required = false, defaultValue = "1") Integer current,
            @RequestParam(required = false, defaultValue = "6") Integer size) {

        IPage<Contents> page = new Page<>(current, size);
        IPage<Contents> result = contentsService.getContentsByUserIdPage(userId, page);
        return Result.ok(result);
    }

    /**
     * 收藏内容
     * @param userId
     * @param current
     * @param size
     * @return
     */
    @GetMapping("/getContentByFavorites/{userId}")
    public Result<IPage<Contents>> getContentByFavorites(
            @PathVariable Integer userId,
            @RequestParam(required = false, defaultValue = "1") Integer current,
            @RequestParam(required = false, defaultValue = "6") Integer size) {

        IPage<Contents> page = new Page<>(current, size);
        IPage<Contents> result = contentsService.getContentByFavorites(page,userId);
        return Result.ok(result);
    }

    /**
     * 历史内容
     * @param userId
     * @param current
     * @param size
     * @return
     */
    @GetMapping("/getHistory/{userId}")
    public Result<IPage<Contents>> getHistory(
            @PathVariable Integer userId,
            @RequestParam(required = false, defaultValue = "1") Integer current,
            @RequestParam(required = false, defaultValue = "6") Integer size) {

        IPage<Contents> page = new Page<>(current, size);
        IPage<Contents> result = contentsService.getHistory(page,userId);
        return Result.ok(result);
    }


    /**
     * 发布/修改新闻
     * @param contents
     * @return
     */
    @PostMapping("/saveOrUpdate")
    public Result saveOrUpdate(@RequestBody Contents contents) {
        contentsService.saveOrUpdate(contents);
        return Result.ok();
    }

    /**
     * 删除内容
     * @param
     * @return
     */
    @DeleteMapping("/delete")
    public Result delete(@RequestParam Integer contentId) {
        contentsService.removeById(contentId);
        return Result.ok();
    }



    /**
     * 根据id修改内容状态
     * @param
     * @return
     */
    @PostMapping("/updateStatusCode")
    public Result updateStatus(@RequestParam() Integer contentId) {
        System.out.println(contentId);
        LambdaUpdateWrapper<Contents> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Contents::getContentId,contentId);
        updateWrapper.set(Contents::getStatusCode,2);
        contentsService.update( updateWrapper );
        return Result.ok();
    }
}
